package com.home.duy.code.DAO;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;

import com.home.Entity.Ban;
import com.home.Entity.NhanVien;
import com.home.System.HibernateUtil;
import com.home.duy.code.Abstract.AbstractDAO;

public class NhanVienDAO extends AbstractDAO{
	private Session session;
	private Transaction trans;
	public NhanVienDAO()
	{
		super();
	}
	
	@Override
	public boolean saveOrUpdate(Object obj) {
		return super.saveOrUpdate(obj);
	}

	@Override
	public boolean delete(Object obj) {
		return super.delete(obj);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object findByPk(Class clas, long pk) {
		return super.findByPk(clas, pk);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List findAll(Class clas) {
		return super.findAll(clas);
	}
	
	public int countSizeData()
	{
		startOperation();
		int count = 0;
		try {
			Criteria criteria = session.createCriteria(NhanVien.class);
			criteria.setProjection(Projections.rowCount());
			count = Integer.parseInt(criteria.uniqueResult().toString());
			trans.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return count;
	}
	
	@SuppressWarnings("unchecked")
	public List<NhanVien> findByPaging(int maxResult,int from) {
		startOperation();
		List<NhanVien> list = null;
		try {
			list = session.createCriteria(NhanVien.class).setMaxResults(maxResult).setFirstResult(from).list();
			trans.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return list;
	}
	
	public NhanVien findByFirstRecord() {
		startOperation();
		NhanVien nv = null;
		try {
			nv = (NhanVien)session.createSQLQuery("SELECT TOP 1* FROM NHANVIEN").addEntity(NhanVien.class).uniqueResult();
			trans.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return nv;
	}
	
	private void startOperation()
	{
		session = HibernateUtil.getSessionFactory().openSession();
		trans = session.beginTransaction();
	}
}
